package com.baoxin.chenxixc4coach.fragments;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baoxin.chenxixc4coach.CoachReadActivity;
import com.baoxin.chenxixc4coach.ContactUsActivity;
import com.baoxin.chenxixc4coach.GlideApp;
import com.baoxin.chenxixc4coach.HelpActivity;
import com.baoxin.chenxixc4coach.IdentifyActivity;
import com.baoxin.chenxixc4coach.LoginActivity;

import com.baoxin.chenxixc4coach.MyApplication;
import com.baoxin.chenxixc4coach.MyCallback;
import com.baoxin.chenxixc4coach.MyCarActivity;
import com.baoxin.chenxixc4coach.MyVideoActivity;
import com.baoxin.chenxixc4coach.R;
import com.baoxin.chenxixc4coach.bean.UserInfo;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.Msg;
import com.baoxin.chenxixc4coach.utils.MyLog;
import com.baoxin.chenxixc4coach.utils.NetUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MyInfoFragment extends BaseFragment implements View.OnClickListener {

    private ImageView mUserIcon;
    private TextView mUserName;
    private TextView mBelong;

    private RelativeLayout mMycar;
    private RelativeLayout mContactUs;
    private RelativeLayout mMyVideo;
    private RelativeLayout mHelp;
    private RelativeLayout mCoachRead;

    UserInfo userInfo;
    private Handler handler;
    private boolean identified_tag = false;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle bundle = msg.getData();
                switch (msg.what) {
                    case Msg.REQUEST_SUCCEED:
                        userInfo = bundle.getParcelable("userInfo");

                        if (!identified_tag) {
                            mUserName.setOnClickListener(new View.OnClickListener() {//未认证
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(getActivity(), IdentifyActivity.class);
                                    startActivity(intent);
                                }
                            });
                        }
                        GlideApp.with(activity)
                                .load(userInfo.getPhoto())
                                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                .error(R.drawable.default_)
                                .into(mUserIcon);

                        mUserName.setText(userInfo.getUserName());
                        mBelong.setText(userInfo.getSchName());
                        mUserIcon.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //打开本地照片库
                                Intent i = new Intent(Intent.ACTION_PICK,
                                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                                startActivityForResult(i, 1);
                            }
                        });
                        break;
                    case Msg.ONFAILURE:
                    case Msg.REQUEST_FAILED:
                        Glide.with(activity)
                                .load(R.drawable.un_login_in)
                                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                                .into(mUserIcon);
                        mUserName.setText("未登录");
                        //to登录界面
                        mUserIcon.setOnClickListener(MyInfoFragment.this);
                        mUserName.setOnClickListener(MyInfoFragment.this);
                        break;
                }
            }
        };
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_myinfo,
                container, false);

        mUserIcon = view.findViewById(R.id.user_icon);
        mUserName = view.findViewById(R.id.user_name);
        mBelong = view.findViewById(R.id.belong);
        mMycar = view.findViewById(R.id.my_car);
        mContactUs = view.findViewById(R.id.contact_us);
        mMyVideo = view.findViewById(R.id.my_video);
        mHelp = view.findViewById(R.id.help);
        mCoachRead = view.findViewById(R.id.coach_read);
        mMycar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MyCarActivity.class);
                startActivity(intent);
            }
        });
        mContactUs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), ContactUsActivity.class);
                startActivity(i);
            }
        });
        mMyVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MyVideoActivity.class);
                startActivity(intent);
            }
        });
        mHelp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HelpActivity.class);
                startActivity(intent);
            }
        });
        mCoachRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), CoachReadActivity.class);
                startActivity(intent);
            }
        });

        update();
        return view;
    }

    public void update() {
        try {
            NetUtil.get(getContext(), Interfaces.URL_USER_INFO, new MyCallback(Interfaces.URL_USER_INFO, handler));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        //未登录--登录--返回 更新头像信息
        if (resultCode == Msg.LOGIN_SUCCEED) {
            update();
        } else {//选择图片后的返回
            if (data == null) return;
            Uri selectedImage = data.getData();

            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = activity.getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String localPicPath = cursor.getString(columnIndex);

            upload(localPicPath);
        }
    }

    private void upload(final String localPicPath) {

        final String netPicPath = "avatar/" + Math.random();
        PutObjectRequest put = new PutObjectRequest("bxpeter", netPicPath, localPicPath);

        OSSAsyncTask task = MyApplication.oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());

                photoChanged(netPicPath);

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
    }

    /**
     * 通知后台用户头像发生变化
     */
    private void photoChanged(String netPicPath) {

        JSONObject body = new JSONObject();
        try {
            body.put("photo", netPicPath);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            NetUtil.post(activity, Interfaces.BASE_USERINFO_CHANGED, body.toString(), new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    MyLog.d("aaa", "onFailure");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    MyLog.d("aaa", response.body().string());
                    update();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.user_icon:
            case R.id.name:
                intent = new Intent(getActivity(), LoginActivity.class);
                startActivityForResult(intent, 1);
                break;
        }

    }


}
